package com.example.CarManagement.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.CarManagement.common.Result;
import com.example.CarManagement.sys.entity.Permission;
import com.example.CarManagement.sys.entity.Role;
import com.example.CarManagement.sys.entity.RolePermission;
import com.example.CarManagement.sys.entity.UserRole;
import com.example.CarManagement.sys.mapper.PermissionMapper;
import com.example.CarManagement.sys.mapper.RoleMapper;
import com.example.CarManagement.sys.mapper.RolePermissionMapper;
import com.example.CarManagement.sys.mapper.UserRoleMapper;
import com.example.CarManagement.sys.service.IRoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * <p>
 * 角色表 服务实现类
 * </p>
 *
 * @author 徐佳彪
 * @since 2025-07-11
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements IRoleService {
    @Resource
    private PermissionMapper permissionMapper;

    // 角色权限表mapper
    @Resource
    private RolePermissionMapper rolePermissionMapper;


    // 用户角色表mapper
    @Resource
    private UserRoleMapper userRoleMapper;

    // 分页查询角色列表
    public Result<?> getRoleByPage(Integer pageSize, Integer pageNo) {

        Page<Role> rolePage = this.baseMapper.selectPage(new Page<>(pageNo, pageSize), null);

        // 角色总数
        Integer total = (int) rolePage.getTotal();


        List<Role> roles = rolePage.getRecords();

        Map<String, Object> data = new HashMap<>();
        data.put("roles", roles);
        data.put("total", total);

        return Result.success(data);
    }


    public Result<?> updateRole(Role role, List<String> permissionList) {

        // 修改角色
        Role oldRole = this.baseMapper.selectById(role);
        oldRole.setName(role.getName());
        oldRole.setRemark(role.getRemark());
        oldRole.setDefault(role.getDefault());
        System.out.println(role);
        this.baseMapper.updateById(oldRole);

        LambdaQueryWrapper<RolePermission> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(RolePermission::getRoleId, oldRole.getId());

        // 删除原来的角色权限表
        rolePermissionMapper.delete(queryWrapper);

        // 添加新角色权限表
        for (String permission : permissionList) {
            RolePermission rolePermission = new RolePermission();
            rolePermission.setId(UUID.randomUUID().toString());
            rolePermission.setPermissionId(permission);
            rolePermission.setRoleId(oldRole.getId());
            rolePermissionMapper.insert(rolePermission);
        }

        return Result.success("修改成功");

    }

    public Result<?> addRole(Role role, List<String> rolePermissions) {
        role.setId(UUID.randomUUID().toString());
        // 检测是否重名
        LambdaQueryWrapper<Role> roleLambdaQueryWrapper = new LambdaQueryWrapper<>();
        roleLambdaQueryWrapper.eq(Role::getName, role.getName());

        if (this.baseMapper.selectOne(roleLambdaQueryWrapper) != null) {
            return Result.fail("角色已存在");
        }


        role.setId(UUID.randomUUID().toString());
        // 添加角色
        this.baseMapper.insert(role);
        // 添加权限
        for (String rolePermissionId : rolePermissions) {
            RolePermission rolePermission = new RolePermission();
            rolePermission.setId(UUID.randomUUID().toString());
            rolePermission.setRoleId(role.getId());
            rolePermission.setPermissionId(rolePermissionId);

            rolePermissionMapper.insert(rolePermission);
        }

        return Result.success("添加成功");
    }

    @Override
    public Result<?> deleteRole(String id) {

        // 检测是否为系统默认角色
        Role role = this.baseMapper.selectById(id);

        if (role.getDefault()) {
            return Result.fail("该角色为系统默认角色，不能删除");
        }

        // 检测是否绑定角色  如果绑定了则不能删除
        LambdaQueryWrapper<UserRole> userRoleWrapper = new LambdaQueryWrapper<>();
        userRoleWrapper.eq(UserRole::getRoleId, id);
        if (userRoleMapper.selectCount(userRoleWrapper) > 0) {
            return Result.fail("该角色已绑定用户，请先解除绑定");
        }

        // 删除角色权限表
        LambdaQueryWrapper<RolePermission> rolePermissionWrapper = new LambdaQueryWrapper<>();
        rolePermissionWrapper.eq(RolePermission::getRoleId, id);
        rolePermissionMapper.delete(rolePermissionWrapper);

        // 删除角色表
        return this.baseMapper.deleteById(id) > 0 ? Result.success("删除成功") : Result.fail("删除失败");

    }


    public Result<?> getRoleById(String id) {
        // 查询角色
        Role role = this.baseMapper.selectById(id);
        // 查询角色对应的权限
        LambdaQueryWrapper<RolePermission> rolePermissionWrapper = new LambdaQueryWrapper<>();
        rolePermissionWrapper.eq(RolePermission::getRoleId, id);
        List<RolePermission> rolePermissions = rolePermissionMapper.selectList(rolePermissionWrapper);
        List<String> rolePermissionIds = new ArrayList<>();
        for (RolePermission rolePermission : rolePermissions) {
            rolePermissionIds.add(rolePermission.getPermissionId());
        }

        List<Permission> permissions = permissionMapper.selectBatchIds(rolePermissionIds);

        Map<String, Object> data = new HashMap<>();
        data.put("role", role);
        data.put("permissions", permissions);

        return Result.success(data);

    }

    /**
     * 获取用户可选角色列表
     *
     * @return
     */
    public Result<?> getRoleByUserSelectList() {
        List<Role> roles = this.baseMapper.selectList(null);

        List<Map<String, Object>> roleList = new ArrayList<>();

        for (Role role : roles) {
            Map<String, Object> roleData = new HashMap<>();
            roleData.put("value", role.getId());
            roleData.put("label", role.getRemark());
            roleList.add(roleData);
        }

        return Result.success(roleList);
    }

    @Override
    public Role getRoleByUserId(String id) {
        LambdaQueryWrapper<UserRole> queryWrapper = new LambdaQueryWrapper<>();

        queryWrapper.eq(UserRole::getUserId, id);
        UserRole userRole = userRoleMapper.selectOne(queryWrapper);


        return this.baseMapper.selectById(userRole.getRoleId());
    }
}
